package de.akabahn.ebd.fahrplan.io;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import de.akabahn.ebd.fahrplan.structure.Bahnhof;
import de.akabahn.ebd.fahrplan.structure.Fahrplan;
import de.akabahn.ebd.fahrplan.structure.Zuglauf;

/**
 * 
 * @author Christian Schlehuber
 * @version 0.1
 * 
 */
public class FahrplanReader {

    private BufferedReader bufReader;
    private Fahrplan fahrplan;
    private HashMap<String, Bahnhof> bahnhoefe;

    /**
     * 
     * @param file
     *            String contains the filename and path to the file to be read
     */
    public FahrplanReader(String file) {
	try {
	    bufReader = new BufferedReader(new FileReader(file));
	} catch (FileNotFoundException e) {
	    System.err.println("Error while opening: " + file);
	    System.err.println(e.getStackTrace().toString());
	}
    }

    /**
     * 
     * @return
     * @throws IOException
     */
    public Fahrplan loadFromFPL() throws IOException {

	Zuglauf currLauf = new Zuglauf();
	parseLaufHeader(currLauf);
	parseLaufStations(currLauf);

	return null;
    }

    /**
     * 
     * @param zl
     */
    private void parseLaufStations(Zuglauf zl) {
	// TODO Auto-generated method stub

    }

    /**
     * 
     * @param zl
     * @throws IOException
     */
    private void parseLaufHeader(Zuglauf zl) throws IOException {
	boolean foundStations = false;
	while (bufReader.ready() && !foundStations) {
	    bufReader.mark(0);
	    String line = bufReader.readLine();
	    if (line != null) {
		String[] parts = line.split("\t");
		if (parts.length > 2)
		    foundStations = true;
		else
		    resolveFPLValue(zl, parts);
	    }
	}
	bufReader.reset();
    }

    /**
     * 
     * @param zl
     * @param parts
     */
    private void resolveFPLValue(Zuglauf zl, String[] parts) {
	if (parts.length == 2) {
	    String key = parts[0];
	    String val = parts[1];

	} else {
	    System.err
		    .println("This wasn't a valid header information! Data is skipped!");
	}
    }

    /**
     * @return the fahrplan
     * @throws FahrplanReaderException
     * @throws IOException
     */
    public Fahrplan getFahrplan() throws FahrplanReaderException, IOException {
	if (fahrplan == null) {
	    System.out
		    .println("NOTICE: Fahrplan was not loaded before this call. Trying to load now.");
	    loadFromFPL();
	}
	if (fahrplan == null) {
	    throw new FahrplanReaderException(
		    "A Fahrplan could not be loaded. Please check your FPL file.");
	} else {
	    return fahrplan;
	}
    }

    public List<Bahnhof> getBahnhofList() {

	return null;
    }

}
